package com.hcloud.auth.third;


import com.hcloud.auth.api.config.LoginType;
import com.hcloud.auth.api.token.ThirdAuthenticationToken;
import com.hcloud.auth.config.SecurityConstants;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 第三方登录过滤
 * @author hepangui
 */
public class ThirdAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public ThirdAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.LOGIN_THRID, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            LoginType loginType = ThirdLoginUtil.getLoginType(request);
            String param = ThirdLoginUtil.getParam(request,loginType);
            ThirdAuthenticationToken authRequest = new ThirdAuthenticationToken(param,loginType);
            authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

}
